package com.xgl.utils;

import org.apache.commons.codec.binary.Hex;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Md5Utils {
	/**
	 * 利用java原生的类实现SHA256加密
	 * 
	 * @param str
	 *            加密后的报文
	 * @return
	 */
//    public static void main(String args[]) throws UnsupportedEncodingException, NoSuchAlgorithmException {
//        String text = "123456123456";
//        System.out.println(Md5Utils.SHA256(text));
//    }

	
   public static String SHA256(String data) throws UnsupportedEncodingException, NoSuchAlgorithmException {
       MessageDigest digest;
       digest = MessageDigest.getInstance("SHA-256");
       byte[] hash = digest.digest(data.getBytes("UTF-8"));
       String output = Hex.encodeHexString(hash);
//       try {
//           md = MessageDigest.getInstance("SHA-256");
//           md.update(data.getBytes());
//           MessageDigest tc1 = (MessageDigest) md.clone();
//           sha = tc1.digest();
//       } catch (NoSuchAlgorithmException e) {
//           e.printStackTrace();
//       } catch (CloneNotSupportedException e) {
//           e.printStackTrace();
//       }
       return output;
   }

   /**
    * 二行制转字符串
    * @param b
    * @return
    */
   static String byte2hex(byte[] b) {
       String hs="";
       String stmp="";
       for (int n=0;n<b.length;n++) {
           stmp = Integer.toHexString(b[n] & 0XFF);
           if (stmp.length()==1) hs = hs + "0" + stmp;
           else hs = hs + stmp;
       }
       return hs.toUpperCase();
   }
   
	@Override
	public String toString() {
		return "Md5Utils []";
	}
	
	
}
